package com.linsir.lin.controller;

import com.linsir.config.SystemConfig;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Autowired
    private SystemConfig systemConfig;

    @RequestMapping(value = "/login",method = {RequestMethod.GET})
    public String login(ModelMap map)
    {
        map.addAttribute("systemConfig",systemConfig);
        return "login";
    }

    @RequestMapping(value = "/login" ,method = {RequestMethod.POST})
    public String doLogin(String userName, String password, ModelMap model)
    {
        Subject subject= SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userName,password);
        try {
            subject.login(usernamePasswordToken);
            return "redirect:/admin";
        }catch (IncorrectCredentialsException incorrectCredentialsException)
        {
                model.addAttribute("error","用户名或密码不正确！");
        }
        catch (UnknownAccountException unknownAccountException)
        {
            model.addAttribute("logininfo","未知账户！");
        }catch(LockedAccountException lae){

            model.addAttribute("logininfo","账户已锁定！");
        }catch(ExcessiveAttemptsException eae){

            model.addAttribute("logininfo","用户名或密码错误次数太多！");
        }catch(AuthenticationException ae){
            ae.printStackTrace();
            model.addAttribute("logininfo","验证未通过！");
        }catch (Exception e) {
            model.addAttribute("logininfo","验证未通过！");
        }
        model.addAttribute("systemConfig",systemConfig);
        return "login";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session, Model model) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        model.addAttribute("msg","安全退出！");
        return "login";
    }
}
